----------------------------------------------------------------------------------------------------------
-- Lootomatic
-- 
-- written by PetraAreon
-- released under the Creative Commons License By-Nc-Sa: http://creativecommons.org/licenses/by-nc-sa/3.0/
--
-- Get the current version at:   http://rom.curse.com/downloads/rom-addons/details/lootomatic.aspx
----------------------------------------------------------------------------------------------------------

function Lootomatic_OnLoad(this)
	local Sol = LibStub("Sol");

	local BootyCloseTimer = nil;
	Lootomatic = {
		Name        = "Lootomatic",
		Version     = "v0.2",
		Loaded      = false;
		MissingLang = nil;
		Timer       = 0,
		Defaults    =
			{
			AM            = true,	-- Enabled in AddonManager?
			Enabled       = true,	-- Lootomatic enabled?
			Interval      = 1,
			Roll          = 3,
			AutoLoot      = 3,
			AutoLootBoss  = false,
			AutoPass      = 1,
			AutoGreed     = 1,
-- 			ChatOutput    = true,
			ItemFilter    = {},
			},
		};

	Lootomatic.Language = string.upper(string.sub(GetLanguage(),1,2));

	local func, err = loadfile("Interface/Addons/Lootomatic/Locales/"..Lootomatic.Language..".lua");
	if (err) then
		dofile("Interface/Addons/Lootomatic/Locales/EN.lua");
		Lootomatic.MissingLang = Lootomatic.Language;
		Lootomatic.Language    = "EN";
	else
		dofile("Interface/Addons/Lootomatic/Locales/"..Lootomatic.Language..".lua");
	end;

	Lootomatic.ListEntries =
		{
		"|cffaaaaaa"                                  ..Lootomatic.Strings.Q1.."|r",
		"|cff"..GetColorString(GetItemQualityColor(0))..Lootomatic.Strings.Q2.."|r",
		"|cff"..GetColorString(GetItemQualityColor(1))..ITEM_QUALITY1_DESC.."|r",
		"|cff"..GetColorString(GetItemQualityColor(2))..ITEM_QUALITY2_DESC.."|r",
		"|cff"..GetColorString(GetItemQualityColor(3))..ITEM_QUALITY3_DESC.."|r",
		"|cff"..GetColorString(GetItemQualityColor(4))..ITEM_QUALITY4_DESC.."|r",
		"|cff"..GetColorString(GetItemQualityColor(5))..ITEM_QUALITY5_DESC.."|r",
		};

 	this:RegisterEvent("VARIABLES_LOADED");
	this:RegisterEvent("BOOTY_SHOW");
	this:RegisterEvent("CHAT_MSG_SYSTEM_GET");

	SLASH_LOOTOMATIC1 = "/lootomatic";
	SlashCmdList["LOOTOMATIC"] = Lootomatic_ToggleItemfilter;
end;

function Lootomatic_OnEvent(event)
	    if (event == "VARIABLES_LOADED") then
		if (Lootomatic_Settings == nil) then
			Lootomatic_Settings = Lootomatic.Defaults;
		else
			if (Lootomatic.Version ~= Lootomatic_Settings.Version) then
				DEFAULT_CHAT_FRAME:AddMessage("|cffFFFE80["..Lootomatic.Name.."]:|r "..string.gsub(Lootomatic.Strings.Updated,"#VERSION#",Lootomatic.Version),0.7,0.7,0.7);

				local Transfer_ItemFilter = Lootomatic_Settings.ItemFilter;

				Lootomatic_Settings = Lootomatic.Defaults;

				Lootomatic_Settings.ItemFilter = Transfer_ItemFilter;
			end;
		end;
		Lootomatic_Settings.Version = Lootomatic.Version;

		if (AddonManager) then
			local addon = {
				name = "Lootomatic",
				version = Lootomatic.Version,
				author = "PetraAreon",
				description = Lootomatic.Strings.Description,
				icon = "Interface/Addons/Lootomatic/Textures/minimap-normal.png",
				category = "Inventory",
				configFrame = LootomaticItemfilter, 
				slashCommands = SLASH_LOOTOMATIC1,
				disableScript = Lootomatic_Disable,
				enableScript = Lootomatic_Enable,
			};
			if (AddonManager.RegisterAddonTable) then
				AddonManager.RegisterAddonTable(addon);
			else
				AddonManager.RegisterAddon(addon.name, addon.description, addon.icon, addon.category, addon.configFrame, addon.slashCommands, addon.miniButton, addon.version, addon.author);
			end;
		else
			DEFAULT_CHAT_FRAME:AddMessage("|cffFFFE80["..Lootomatic.Name.." "..Lootomatic.Version.."]:|r "..Lootomatic.Strings.Loaded,0.7,0.7,0.7);
		end;

		if (Lootomatic.MissingLang ~= nil) then
			DEFAULT_CHAT_FRAME:AddMessage("|cffFFFE80["..Lootomatic.Name.." "..Lootomatic.Version.."]:|r No locales found for your language \""..Lootomatic.MissingLang.."\", switching to fallback \"EN\". If you want your language to be added, please contact the author PetraAreon ;-)",0.7,0.7,0.7);
		end;

		LootomaticItemfilter:SetSize(400,250);

		LootomaticItemfilter_Header        :SetText(Lootomatic.Strings.ItemfilterHeader);
		LootomaticItemfilter_Itemname_Title:SetText(Lootomatic.Strings.Itemname);
		LootomaticItemfilter_Looting_Title :SetText(Lootomatic.Strings.Looting);
		LootomaticItemfilter_Rolling_Title :SetText(Lootomatic.Strings.Rolling);

	 	UIDropDownMenu_Initialize   (Lootomatic_Dropdown, Lootomatic_MinimapList);
		UIDropDownMenu_Initialize   (LootomaticItemfilter_Looting, Lootomatic_LootmenuItems);
		UIDropDownMenu_SetSelectedID(LootomaticItemfilter_Looting, 1);
		UIDropDownMenu_Initialize   (LootomaticItemfilter_Rolling, Lootomatic_RollmenuItems);
		UIDropDownMenu_SetSelectedID(LootomaticItemfilter_Rolling, 1);

		----------------------------------------------------------------------------------------------------
		--                       !WARNING! Modifying Original Content                                     --
		----------------------------------------------------------------------------------------------------
		Sol.hooks.Hook("Lootomatic", "BagItemButton_OnClick", Lootomatic_BagItemButton_OnClick, nil);     --
		UIDropDownMenu_Initialize(PlayerFrameDropDown, Lootomatic_PlayerFrameDropDown,    "MENU");        -- Manipulating Dropdowns via Sol not possible,
		UIDropDownMenu_Initialize(ChatFrameDropDown,   Lootomatic_ChatFrameDropDown_Show, "MENU");        -- because initialization won't be overwritten
		----------------------------------------------------------------------------------------------------

	 	SaveVariables("Lootomatic_Settings");
		Lootomatic.Loaded = true;

	elseif (Lootomatic.Loaded == true and event == "BOOTY_SHOW") then
		if (Lootomatic_Settings.Enabled == true and (not AddonManager or Lootomatic_Settings.AM == true)) then
			local a,b = GetCursorPos();
			local c,d = BootyFrame:GetSize();
			BootyFrame:SetPos(a-c*0.5*GetUIScale(),b-d*0.5*GetUIScale());
			Lootomatic_CheckBootyFrame();
		end;
	elseif (Lootomatic.Loaded == true and event == "CHAT_MSG_SYSTEM_GET") then
 		if (Lootomatic_Settings.Enabled == true and (not AddonManager or Lootomatic_Settings.AM == true)) then
--  			if (Lootomatic_Settings.ChatOutput == true) then
-- 				DEFAULT_CHAT_FRAME:AddMessage("[Loot]: "..string.gsub(arg1,"^.*\|H","|H"));
--  			end;
 			Lootomatic_DropGarbage();
 		end;
	end;
end;

function Lootomatic_OnUpdate(elapsedTime)
	if (Lootomatic.Loaded == true) then
		if (BootyCloseTimer ~= nil) then
			if (GetTickCount()-BootyCloseTimer>500) then BootyFrame:Hide(); BootyCloseTimer=nil; end;
		end;

		if (Lootomatic_Settings.Enabled == true and (not AddonManager or Lootomatic_Settings.AM == true)) then
			Lootomatic.Timer = Lootomatic.Timer + elapsedTime;
			if (Lootomatic.Timer >= Lootomatic_Settings.Interval) then
				Lootomatic.Timer = 0;
	
				if (Lootomatic_Settings.Roll ~= GetLootThreshold()+2) then
					Lootomatic_Settings.Roll = GetLootThreshold()+2;
					DEFAULT_CHAT_FRAME:AddMessage("|cffFFFE80["..Lootomatic.Name.."]:|r "..string.gsub(Lootomatic.Strings.RollChange,"#ROLLSETTING#","["..Lootomatic.ListEntries[Lootomatic_Settings.Roll].."]"),0.7,0.7,0.7);
				end;
	
				if (GroupLootFrame1:IsVisible() == true) then Lootomatic_CheckRollFrame(GroupLootFrame1.lootIndex); end;
				if (GroupLootFrame2:IsVisible() == true) then Lootomatic_CheckRollFrame(GroupLootFrame2.lootIndex); end;
				if (GroupLootFrame3:IsVisible() == true) then Lootomatic_CheckRollFrame(GroupLootFrame3.lootIndex); end;
				if (GroupLootFrame4:IsVisible() == true) then Lootomatic_CheckRollFrame(GroupLootFrame4.lootIndex); end;
				if (GroupLootFrame5:IsVisible() == true) then Lootomatic_CheckRollFrame(GroupLootFrame5.lootIndex); end;
				if (GroupLootFrame6:IsVisible() == true) then Lootomatic_CheckRollFrame(GroupLootFrame6.lootIndex); end;
			end;
		end;
	end;
end;




function Lootomatic_CheckRollFrame(Rollframe)
	if (Rollframe ~= nil) then
		name, icon, itemCount, quality = GetLootRollItemInfo(Rollframe);

		local lootmode = nil;
		if (quality <= Lootomatic_Settings.AutoGreed - 2) then lootmode = "greed"; end;
		if (quality <= Lootomatic_Settings.AutoPass  - 2) then lootmode = "pass";  end;

		for i=1,table.maxn(Lootomatic_Settings.ItemFilter) do
			if (string.match(name, "^"..string.gsub(string.gsub(Lootomatic_Settings.ItemFilter[i]["Name"], "(%W)", "%%%1"),"%%%*",".*").."$") ~= nil) then
				    if (Lootomatic_Settings.ItemFilter[i]["Roll"]==2) then lootmode="pass";
				elseif (Lootomatic_Settings.ItemFilter[i]["Roll"]==3) then lootmode="greed";
				elseif (Lootomatic_Settings.ItemFilter[i]["Roll"]==4) then lootmode="roll"; end;
			end;
		end;

		if (lootmode ~= nil) then
			RollOnLoot(Rollframe, lootmode);
		end;
	end;
end;

function Lootomatic_CheckBootyFrame()
	local closeframe = true;
	if (not IsShiftKeyDown()) then
		--IsAltKeyDown()
		--IsCtrlKeyDown()
		if (not(UnitSex("target")==3 and Lootomatic_Settings.AutoLootBoss==false)) then
			local i=0;
			while true do
				i=i+1;
				texture, name, count, quality = GetBootyItemInfo(i);
				if (name ~= nil and quality ~= nil) then
					local loot = false;
		
					if (quality <= Lootomatic_Settings.AutoLoot - 2) then loot = true; else closeframe = false; end;
		
					for j=1,table.maxn(Lootomatic_Settings.ItemFilter) do
						if (string.match(name, "^"..string.gsub(string.gsub(Lootomatic_Settings.ItemFilter[j]["Name"], "(%W)", "%%%1"),"%%%*",".*").."$") ~= nil) then
							    if (Lootomatic_Settings.ItemFilter[j]["Loot"]==2) then loot = false;
							elseif (Lootomatic_Settings.ItemFilter[j]["Loot"]> 2) then loot = true; end;
						end;
					end;
					if (loot == true) then ClickBootyItem(i); end;
				else
					break;
				end;
 			if (closeframe) then BootyCloseTimer = GetTickCount(); end;
			end;
		end;
	end;
end;

function Lootomatic_DropGarbage()
	local garbagecount = 0;
	local bagitems, bagsize = GetBagCount();
	for i = 1,bagsize do
		local id, icon, name, count = GetBagItemInfo(i)
		if ( id and name ) then
			RemoveGarbageItem(id);
			for j=1,table.maxn(Lootomatic_Settings.ItemFilter) do
				if (string.match(name, "^"..string.gsub(string.gsub(Lootomatic_Settings.ItemFilter[j]["Name"], "(%W)", "%%%1"),"%%%*",".*").."$") ~= nil) then
					if (Lootomatic_Settings.ItemFilter[j]["Loot"]==4) then
						InsertGarbageItem(id);
						garbagecount = garbagecount + 1;
					end;
				end;
			end;
		end;
	end;

	    if (garbagecount>3) then
		GarbageFrame:Show();
		StaticPopup_Show("DELETE_GARBAGE_ITEM");
 	elseif (garbagecount>0) then
 		DeleteGarbageItems();
 		GarbageFrame:Hide();
	end;
end;

----------------------------------------------------------------------------------------------------
-------------------- New content/behaviour of original frames --------------------------------------
----------------------------------------------------------------------------------------------------

function Lootomatic_BagItemButton_OnClick(frame, button, ignoreShift)
	if (button=="LBUTTON" and IsShiftKeyDown() and LootomaticItemfilter:IsVisible()) then
		local index, file, name, itemCount, locked = GetBagItemInfo(frame:GetID());
		if (name) then Lootomatic_AddFilter(name); end;
	else
		Sol.hooks.GetOriginalFn("Lootomatic", "BagItemButton_OnClick") (frame, button, ignoreShift)
	end;
end;

function Lootomatic_PlayerFrameDropDown(this)
	if ( UIDROPDOWNMENU_MENU_LEVEL == 2 and UIDROPDOWNMENU_MENU_VALUE == "LOOT_THRESHOLD") then
		menuitem = {};
		local r, g, b = GetItemQualityColor(0);
		menuitem.textR = r;
		menuitem.textG = g;
		menuitem.textB = b;
		menuitem.text = Lootomatic.Strings["Q2"];
		if (GetLootThreshold() == 0) then menuitem.checked = 1;
		                             else menuitem.checked = nil; end;
		menuitem.func = function () SetLootThreshold(0); CloseDropDownMenus(1); end;
		UIDropDownMenu_AddButton( menuitem, 2 );
	end;

	PlayerFrameDropDown_Show(); -- Entries of the original Popup-Menue Characterframe

	if ( UIDROPDOWNMENU_MENU_LEVEL == 2 and UIDROPDOWNMENU_MENU_VALUE == "LOOT_THRESHOLD") then
		menuitem = {};
		local r, g, b = GetItemQualityColor(5);
		menuitem.textR = r;
		menuitem.textG = g;
		menuitem.textB = b;
		menuitem.text = ITEM_QUALITY5_DESC;
		if (GetLootThreshold() == 5) then menuitem.checked = 1;
		                             else menuitem.checked = nil; end;
		menuitem.func = function () SetLootThreshold(5); CloseDropDownMenus(1); end;
		UIDropDownMenu_AddButton( menuitem, 2 );
	end;

end;

function Lootomatic_ChatFrameDropDown_Show(this)
	ChatFrameDropDown_Show(this); -- Entries of the original Popup-Menue ChatFrame

	if ( ChatFrameDropDown.hyperlinkType == "item" ) then
		menuitem = {};
		menuitem.text = "|cffFFFE80[Lootomatic]:|r "..Lootomatic.Strings.AddFilter;
		menuitem.func = function() Lootomatic_AddFilter(this._name); end;
		UIDropDownMenu_AddButton( menuitem, 1 );
	end;
end;



----------------------------------------------------------------------------------------------------
-------------------- Minimap-Menue -----------------------------------------------------------------
----------------------------------------------------------------------------------------------------

function Lootomatic_MinimapList()
	if (UIDROPDOWNMENU_MENU_LEVEL == 1) then
		local menuitem = {};
		menuitem.func = Lootomatic_Toggle;
		if (Lootomatic_Settings.Enabled==true) then menuitem.text = Lootomatic.Strings.MEnabled;  menuitem.checked = 1;
		                                       else menuitem.text = Lootomatic.Strings.MDisabled; menuitem.checked = nil; end;
		UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);

		local menuitem = {};
		menuitem.notCheckable = 1;

		menuitem.value = 1;
		if (IsPartyLeader("player")~=true) then menuitem.disabled = true; else menuitem.hasArrow = 1; end;
		menuitem.text = Lootomatic.Strings.Roll     ..": "..Lootomatic.ListEntries[GetLootThreshold()+2];
		UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);

		menuitem.value = 2;
		menuitem.hasArrow = 1;
		menuitem.disabled = nil;
		menuitem.text = Lootomatic.Strings.AutoLoot ..": "..Lootomatic.ListEntries[Lootomatic_Settings.AutoLoot];
		UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);

		menuitem.value = 3;
		menuitem.text = Lootomatic.Strings.AutoPass ..": "..Lootomatic.ListEntries[Lootomatic_Settings.AutoPass];
		UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);

		menuitem.value = 4;
		menuitem.text = Lootomatic.Strings.AutoGreed..": "..Lootomatic.ListEntries[Lootomatic_Settings.AutoGreed];
		UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);

		local menuitem = {};
		menuitem.notCheckable = 1;
		menuitem.text = "Itemfilter";
		menuitem.func = Lootomatic_ToggleItemfilter;
		UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);
	else
		local menuitem = {};
		if (UIDROPDOWNMENU_MENU_VALUE == 1) then
			for i=2,7 do
				menuitem.text = Lootomatic.ListEntries[i];
				menuitem.func = function() SetLootThreshold(i-2); CloseDropDownMenus(1); ToggleDropDownMenu(Lootomatic_Dropdown); end;
				if (GetLootThreshold()+2==i) then menuitem.checked = 1;
				                             else menuitem.checked = nil; end;
				UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);
			end;
		elseif (UIDROPDOWNMENU_MENU_VALUE == 2) then
			for i=1,7 do
				menuitem.text = Lootomatic.ListEntries[i];
				menuitem.func = function() Lootomatic_Settings.AutoLoot = i; CloseDropDownMenus(1); ToggleDropDownMenu(Lootomatic_Dropdown); end;
				if (Lootomatic_Settings.AutoLoot==i) then menuitem.checked = 1;
				                                     else menuitem.checked = nil; end;
				UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);
			end;
			menuitem = {};
			menuitem.isTitle = true;
			UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);

			menuitem = {};
			menuitem.text = "Keine Bosse";
			menuitem.func = function() Lootomatic_Settings.AutoLootBoss = not Lootomatic_Settings.AutoLootBoss; CloseDropDownMenus(1); ToggleDropDownMenu(Lootomatic_Dropdown); end;
			if (Lootomatic_Settings.AutoLootBoss==false) then menuitem.checked = 1;
			                                             else menuitem.checked = nil; end;
			UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);
		elseif (UIDROPDOWNMENU_MENU_VALUE == 3) then
			for i=1,7 do
				menuitem.text = Lootomatic.ListEntries[i];
				menuitem.func = function() Lootomatic_Settings.AutoPass = i; CloseDropDownMenus(1); ToggleDropDownMenu(Lootomatic_Dropdown); end;
				if (Lootomatic_Settings.AutoPass==i) then menuitem.checked = 1;
				                                     else menuitem.checked = nil; end;
				UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);
			end;
		elseif (UIDROPDOWNMENU_MENU_VALUE == 4) then
			for i=1,7 do
				menuitem.text = Lootomatic.ListEntries[i];
				menuitem.func = function() Lootomatic_Settings.AutoGreed = i; CloseDropDownMenus(1); ToggleDropDownMenu(Lootomatic_Dropdown); end;
				if (Lootomatic_Settings.AutoGreed==i) then menuitem.checked = 1;
				                                      else menuitem.checked = nil; end;
				UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL);
			end;
		end;
	end;
end;





----------------------------------------------------------------------------------------------------
-------------------- Miscallaneous -----------------------------------------------------------------
----------------------------------------------------------------------------------------------------

function GetColorString(r,g,b)
	return string.format('%02x%02x%02x',r*255,g*255,b*255);
end;

function Lootomatic_Tooltip(Object)
	GameTooltip:SetOwner(Object,"ANCHOR_BOTTOM",0,0);
	GameTooltip:ClearAllAnchors();
	GameTooltip:SetAnchor("TOPLEFT","TOPRIGHT",Object,-2,-2);

	if (Object:GetName()=="Lootomatic_Minimap") then
		GameTooltip:SetText("|cffFFFE80"..Lootomatic.Name.." "..Lootomatic.Version.."|r");
	
		if (Lootomatic_Settings.Enabled == true) then GameTooltip:AddLine("   "..Lootomatic.Strings.Enabled ,0,1,0);
		                                         else GameTooltip:AddLine("   "..Lootomatic.Strings.Disabled,1,0,0); end;

		local bosses = "";
		if (Lootomatic_Settings.AutoLootBoss == false) then bosses = ", Keine Bosse"; end;

		GameTooltip:AddLine("   "..Lootomatic.Strings.Roll     ..": "..Lootomatic.ListEntries[Lootomatic_Settings.Roll]);
		GameTooltip:AddLine("   "..Lootomatic.Strings.AutoLoot ..": "..Lootomatic.ListEntries[Lootomatic_Settings.AutoLoot]..bosses);
		GameTooltip:AddLine("   "..Lootomatic.Strings.AutoPass ..": "..Lootomatic.ListEntries[Lootomatic_Settings.AutoPass]);
		GameTooltip:AddLine("   "..Lootomatic.Strings.AutoGreed..": "..Lootomatic.ListEntries[Lootomatic_Settings.AutoGreed]);
	
	            GameTooltip:AddLine(UI_MINIMAPBUTTON_MOVE, 0, 0.75, 0.95);
	else
		GameTooltip:SetText("|cffFFFE80"..Lootomatic.Strings["Tooltip_"..Object:GetName()][1].."|r");
		GameTooltip:AddLine(              Lootomatic.Strings["Tooltip_"..Object:GetName()][2]      );

		if (table.maxn(Lootomatic.Strings["Tooltip_"..Object:GetName()])>2) then
			if (IsShiftKeyDown()) then GameTooltip:AddLine(Lootomatic.Strings["Tooltip_"..Object:GetName()][3]);
			                      else GameTooltip:AddLine(Lootomatic.Strings["Tooltip_LongText"], 0, 0.75, 0.95); end;
		end;
	end;
end;

function Lootomatic_Toggle()
	if (Lootomatic_Settings.Enabled == true) then Lootomatic_Settings.Enabled = false;
	                                         else Lootomatic_Settings.Enabled = true; end;
end;
function Lootomatic_Enable()
	Lootomatic_Settings.AM = true;
	Lootomatic_Minimap:Show();
end;
function Lootomatic_Disable()
	Lootomatic_Settings.AM = false;
	Lootomatic_Minimap:Hide();
end;





----------------------------------------------------------------------------------------------------
-------------------- Item Filter -------------------------------------------------------------------
----------------------------------------------------------------------------------------------------

function Lootomatic_ToggleItemfilter()
	if (LootomaticItemfilter:IsVisible()) then LootomaticItemfilter:Hide();
		                          else LootomaticItemfilter:Show();end;
end;

function Lootomatic_RefreshItemfilter()
	table.sort(Lootomatic_Settings.ItemFilter,Lootomatic_Itemfilter_ListSort);

	local a,b = LootomaticItemfilter_Filterlist:GetSize();
	local maxvalues = math.floor((b-20)/20);

	local maxvalue = table.maxn(Lootomatic_Settings.ItemFilter)-(maxvalues-1);
	if (maxvalue < 1 ) then maxvalue = 1; end;

	if (maxvalue==1) then LootomaticItemfilter_Filterlist_ScrollBar:Hide();
	                 else LootomaticItemfilter_Filterlist_ScrollBar:Show(); end;

	LootomaticItemfilter_Filterlist_ScrollBar:SetMinMaxValues(1,maxvalue);
	local value = LootomaticItemfilter_Filterlist_ScrollBar:GetValue();

	for i=1,30 do
		if (i <= maxvalues) then
			getglobal("LootomaticItemfilter_Filterlist_Item"..i):Show();
		else
			getglobal("LootomaticItemfilter_Filterlist_Item"..i):Hide();
		end;

		if (value-1+i <= table.maxn(Lootomatic_Settings.ItemFilter)) then
			getglobal("LootomaticItemfilter_Filterlist_Item"..i.."_Name"):SetText(tostring(                              Lootomatic_Settings.ItemFilter[(value-1+i)].Name ));
			getglobal("LootomaticItemfilter_Filterlist_Item"..i.."_Loot"):SetText(tostring(Lootomatic.Strings.LootStatus[Lootomatic_Settings.ItemFilter[(value-1+i)].Loot]));
			getglobal("LootomaticItemfilter_Filterlist_Item"..i.."_Roll"):SetText(tostring(Lootomatic.Strings.RollStatus[Lootomatic_Settings.ItemFilter[(value-1+i)].Roll]));
		else
			getglobal("LootomaticItemfilter_Filterlist_Item"..i.."_Name"):SetText("");
			getglobal("LootomaticItemfilter_Filterlist_Item"..i.."_Loot"):SetText("");
			getglobal("LootomaticItemfilter_Filterlist_Item"..i.."_Roll"):SetText("");
		end;
	end;

	local a,b = LootomaticItemfilter:GetPos();
	local c,d = LootomaticItemfilter:GetSize();
	LootomaticItemfilter_ResizeButton:SetPos(a+(c-19)*GetUIScale(),b+(d-19)*GetUIScale());

	Lootomatic_Itemfilter_NameChanged();
end;

function Lootomatic_LootmenuItems()
	local menuitem;

	menuitem = {};
	menuitem.text = Lootomatic.Strings.LootStatus[1];
	menuitem.func = function() Lootomatic_Itemfilter_LootChanged(1); end;
	UIDropDownMenu_AddButton(menuitem,1);

	menuitem = {};
	menuitem.text = Lootomatic.Strings.LootStatus[2];
	menuitem.func = function() Lootomatic_Itemfilter_LootChanged(2); end;
	UIDropDownMenu_AddButton(menuitem,1);

	menuitem = {};
	menuitem.text = Lootomatic.Strings.LootStatus[3];
	menuitem.func = function() Lootomatic_Itemfilter_LootChanged(3); end;
	UIDropDownMenu_AddButton(menuitem,1);

	menuitem = {};
	menuitem.text = Lootomatic.Strings.LootStatus[4];
	menuitem.func = function() Lootomatic_Itemfilter_LootChanged(4); end;
	UIDropDownMenu_AddButton(menuitem,1);
end;

function Lootomatic_RollmenuItems()
	local menuitem;

	menuitem = {};
	menuitem.text = Lootomatic.Strings.RollStatus[1];
	menuitem.func = function() Lootomatic_Itemfilter_RollChanged(1); end;
	UIDropDownMenu_AddButton(menuitem,1);

	menuitem = {};
	menuitem.text = Lootomatic.Strings.RollStatus[2];
	menuitem.func = function() Lootomatic_Itemfilter_RollChanged(2); end;
	UIDropDownMenu_AddButton(menuitem,1);

	menuitem = {};
	menuitem.text = Lootomatic.Strings.RollStatus[3];
	menuitem.func = function() Lootomatic_Itemfilter_RollChanged(3); end;
	UIDropDownMenu_AddButton(menuitem,1);

	menuitem = {};
	menuitem.text = Lootomatic.Strings.RollStatus[4];
	menuitem.func = function() Lootomatic_Itemfilter_RollChanged(4); end;
	UIDropDownMenu_AddButton(menuitem,1);
end;

function Lootomatic_Itemfilter_NameChanged()
	local found = nil;

	for i=1,table.maxn(Lootomatic_Settings.ItemFilter) do
		if (Lootomatic_Settings.ItemFilter[i]["Name"] == LootomaticItemfilter_Itemname:GetText()) then
			found = i;

			UIDropDownMenu_SetSelectedID(LootomaticItemfilter_Looting, Lootomatic_Settings.ItemFilter[i]["Loot"]);
			UIDropDownMenu_SetText      (LootomaticItemfilter_Looting, Lootomatic.Strings.LootStatus[Lootomatic_Settings.ItemFilter[i]["Loot"]]);

			UIDropDownMenu_SetSelectedID(LootomaticItemfilter_Rolling, Lootomatic_Settings.ItemFilter[i]["Roll"]);
			UIDropDownMenu_SetText      (LootomaticItemfilter_Rolling, Lootomatic.Strings.RollStatus[Lootomatic_Settings.ItemFilter[i]["Roll"]]);
			break;
		end;
	end;

	    if (found == nil) then
		LootomaticItemfilter_Itemname_Text:SetColor(1,1,1);
		LootomaticItemfilter_ItemAdd      :Show();
		LootomaticItemfilter_ItemRemove   :Hide();

		if (string.len(LootomaticItemfilter_Itemname:GetText())==0 or (UIDropDownMenu_GetSelectedID(LootomaticItemfilter_Looting) == 1 and UIDropDownMenu_GetSelectedID(LootomaticItemfilter_Rolling) == 1)) then
			LootomaticItemfilter_ItemAdd:Disable();
		else
			LootomaticItemfilter_ItemAdd:Enable();
		end;
	else
		LootomaticItemfilter_Itemname_Text:SetColor(1,0.82,0);
		LootomaticItemfilter_ItemAdd      :Hide();
		LootomaticItemfilter_ItemRemove   :Show();
	end;
end;

function Lootomatic_Itemfilter_LootChanged(set)
	local found = false;

	UIDropDownMenu_SetSelectedID(LootomaticItemfilter_Looting, set);
	
	for i=1,table.maxn(Lootomatic_Settings.ItemFilter) do
		if (Lootomatic_Settings.ItemFilter[i]["Name"] == LootomaticItemfilter_Itemname:GetText()) then
			found = true;
			Lootomatic_Settings.ItemFilter[i]["Loot"] = set;
			break;
		end;
	end;
	Lootomatic_RefreshItemfilter();
end;

function Lootomatic_Itemfilter_RollChanged(set)
	local found = false;

	UIDropDownMenu_SetSelectedID(LootomaticItemfilter_Rolling, set);

	for i=1,table.maxn(Lootomatic_Settings.ItemFilter) do
		if (Lootomatic_Settings.ItemFilter[i]["Name"] == LootomaticItemfilter_Itemname:GetText()) then
			found = true;
			Lootomatic_Settings.ItemFilter[i]["Roll"] = set;
			break;
		end;
	end;
	Lootomatic_RefreshItemfilter();
end;

function Lootomatic_Itemfilter_AddItem()
	table.insert(Lootomatic_Settings.ItemFilter,
		{
		Name = LootomaticItemfilter_Itemname:GetText(),
		Loot = UIDropDownMenu_GetSelectedID(LootomaticItemfilter_Looting),
		Roll = UIDropDownMenu_GetSelectedID(LootomaticItemfilter_Rolling),
		});
	Lootomatic_RefreshItemfilter();
end;

function Lootomatic_Itemfilter_RemoveItem()
	for i=1,table.maxn(Lootomatic_Settings.ItemFilter) do
		if (Lootomatic_Settings.ItemFilter[i]["Name"] == LootomaticItemfilter_Itemname:GetText()) then
			table.remove(Lootomatic_Settings.ItemFilter,i);
			break;
		end;
	end;
	Lootomatic_RefreshItemfilter();
end;

function Lootomatic_Itemfilter_RowClicked(id)
	local itemnumber = LootomaticItemfilter_Filterlist_ScrollBar:GetValue()+id-1;

	LootomaticItemfilter_Itemname:SetText(Lootomatic_Settings.ItemFilter[itemnumber]["Name"]);
	Lootomatic_Itemfilter_NameChanged();
end;

function Lootomatic_Itemfilter_ListSort(a,b)
	if (string.lower(string.gsub(a.Name,"[\* ]","")) < string.lower(string.gsub(b.Name,"[\* ]","")))
		then return true;
		else return false;
		end;
end;

function Lootomatic_Itemfilter_Highlight(Object,mode)
	if (mode==true) then
		getglobal(Object.."_Name"):SetColor(1,0.82,0);
		getglobal(Object.."_Loot"):SetColor(1,0.82,0);
		getglobal(Object.."_Roll"):SetColor(1,0.82,0);
	else
		getglobal(Object.."_Name"):SetColor(1,1   ,1);
		getglobal(Object.."_Loot"):SetColor(1,1   ,1);
		getglobal(Object.."_Roll"):SetColor(1,1   ,1);
	end;
end;

function Lootomatic_AddFilter(name)
	LootomaticItemfilter:Show();
	LootomaticItemfilter_Itemname:SetText(name);

	UIDropDownMenu_SetSelectedID(LootomaticItemfilter_Looting, 1);
	UIDropDownMenu_SetText      (LootomaticItemfilter_Looting, Lootomatic.Strings.LootStatus[1]);

	UIDropDownMenu_SetSelectedID(LootomaticItemfilter_Rolling, 1);
	UIDropDownMenu_SetText      (LootomaticItemfilter_Rolling, Lootomatic.Strings.RollStatus[1]);

	Lootomatic_Itemfilter_NameChanged();
end;

function Lootomatic_ItemFilter_ReceiveDrag(this)
	if ( CursorItemType() == "bag" ) then
		local id = GetCursorItemInfo();
		local icon, name, count = GetGoodsItemInfo(id);
		Lootomatic_AddFilter(name);
		LootomaticItemfilter_Itemname:ClearFocus();
		InsertGarbageItem(id, true);
		RemoveGarbageItem(id);
	end
end;

function Lootomatic_Itemfilter_Scroll(delta)
	    if (delta>0) then LootomaticItemfilter_Filterlist_ScrollBar:SetValue(LootomaticItemfilter_Filterlist_ScrollBar:GetValue()-1);
	elseif (delta<0) then LootomaticItemfilter_Filterlist_ScrollBar:SetValue(LootomaticItemfilter_Filterlist_ScrollBar:GetValue()+1); end;
end;

function Lootomatic_ItemFilterResize()
	local a,b = LootomaticItemfilter:GetPos();
	local c,d = LootomaticItemfilter_ResizeButton:GetPos();

	local x = (c-a+19)/GetUIScale();
	local y = (d-b+19)/GetUIScale();

	if (x<400) then x = 400; end;
	if (y<210) then y = 210; end;

	LootomaticItemfilter:SetSize(x,y);
	LootomaticItemfilter:SetPos(a,b);

	local e,f = LootomaticItemfilter:GetSize();
	LootomaticItemfilter_Filterlist:SetSize(e-40,f-90);
	LootomaticItemfilter_Filterlist_ScrollBar:SetSize(10,f-138);

	Lootomatic_RefreshItemfilter();
end;



-- eof -- Lootomatic, written by PetraAreon